import numpy as np
import pandas as pd
from matplotlib import pyplot as plt


def Mutate_detection(value, prediction, buy_line, sale_line):
    scatter_buy_x = []
    scatter_buy_y = []
    scatter_sale_x = []
    scatter_sale_y = []
    mutate_point_marker = []
    last_buy_value = value[0]
    is_buy = False
    mutate_point_marker.append([None])
    for i in range(1,len(value)):
        past_diff = value[i]-value[i-1]
        predict_diff = (prediction[i] - value[i]) / (7 * value[i])
        # 亏了0.1直接卖
        if (value[i]-last_buy_value)/last_buy_value < -0.1 and is_buy:
            mutate_point_marker.append([0])
            scatter_sale_x.append(i)
            scatter_sale_y.append(value[i])
            is_buy = False
        # print(past_diff, predict_diff)
        elif past_diff*predict_diff < 0:
            if predict_diff > buy_line:
                mutate_point_marker.append([1])
                scatter_buy_x.append(i)
                scatter_buy_y.append(value[i])
                #更新最近成本价
                last_buy_value = value[i]
                is_buy = True
            elif predict_diff < -sale_line:
                mutate_point_marker.append([0])
                scatter_sale_x.append(i)
                scatter_sale_y.append(value[i])
                is_buy = False
            else:
                mutate_point_marker.append([None])
        else:
            mutate_point_marker.append([None])

    return mutate_point_marker, scatter_buy_x, scatter_buy_y, scatter_sale_x, scatter_sale_y


# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
    filename = 'bitcoin'
    data = pd.read_excel("data/"+filename+".xlsx")
    print(data)
    value = data["Value"].values
    # print(value)
    prediction = data["Prediction"].values

    # bitcoin:0.035 ,0.03
    # gold:0.01 ,0.005
    mutate_point_marker, scatter_buy_x, scatter_buy_y, scatter_sale_x, scatter_sale_y = Mutate_detection(value, prediction, 0.035 ,0.03)


    # temp = pd.DataFrame(mutate_result, columns=['mutate'])
    # temp.to_excel('save.xlsx')

    # scatter_sale_y
    plt.figure(figsize=(10, 6))
    plt.scatter(scatter_buy_x, scatter_buy_y, label="buy",  c='green')
    plt.scatter(scatter_sale_x, scatter_sale_y, label="sale", c='red')
    plt.plot(value, label="real")
    plt.xlabel('Date', fontsize=12, verticalalignment='top')
    plt.ylabel('Prices', fontsize=14, horizontalalignment='center')
    plt.legend()
    plt.show()

    mutate_point_marker = pd.DataFrame(mutate_point_marker)
    mutate_point_marker.to_excel(filename+'_predict.xlsx')





